import React, { useEffect, useMemo, useState } from 'react';
import { Button, Input, Modal } from '@/components';
import { templateAPI, DocTemplateDTO, CreateTemplateParams } from '@/utils/api';
import { TEMPLATES } from './templates';

// 根据文档类型获取默认内容
const getDefaultContentByDocType = (docType: string): string => {
  // 查找匹配的模板
  const matchedTemplate = Object.values(TEMPLATES).find(tpl => tpl.docType === docType);
  if (matchedTemplate) {
    return matchedTemplate.content;
  }
  
  // 如果没有匹配的模板，根据常见类型返回默认内容
  switch (docType) {
    case 'sheet':
      return JSON.stringify([
        ['任务', '负责人', '进度(%)'],
        ['需求梳理', '张三', 100],
        ['设计联调', '李四', 60],
        ['功能开发', '王五', 30],
      ], null, 2);
    case 'slide':
      return [
        '# 项目汇报',
        '',
        '---',
        '',
        '## 目标',
        '',
        '- 版本发布',
        '- 指标提升',
        '',
        '---',
        '',
        '## 进度',
        '',
        '- 已完成：需求评审、环境搭建',
        '- 进行中：核心功能开发',
      ].join('\n');
    case 'mindmap':
      return [
        '# 产品规划',
        '',
        '- 目标',
        '  - 提升留存',
        '  - 降低成本',
        '- 路线',
        '  - Q1 基础能力完善',
        '  - Q2 体验优化与扩展',
        '- 风险',
        '  - 资源不足',
        '  - 需求波动',
      ].join('\n');
    default:
      return '<h1>开始你的创作</h1><p>这里是一个空白文档。</p>';
  }
};

interface TemplateManageProps {
   
  onTemplateSelect?: (template: DocTemplateDTO) => void;
}

const TemplateManage: React.FC<TemplateManageProps> = () => {
  const [list, setList] = useState<DocTemplateDTO[]>([]);
  const [, setLoading] = useState(false);
  const [showEdit, setShowEdit] = useState(false);
  const [editing, setEditing] = useState<Partial<DocTemplateDTO> | null>(null);
  const [previousDocType, setPreviousDocType] = useState<string>('');

  const load = async () => {
    setLoading(true);
    try {
      const res = await templateAPI.list();
      // 兼容后端统一响应/或直出数组
      const data = (res as unknown as { data?: DocTemplateDTO[] } & DocTemplateDTO[]).data ?? (res as unknown as DocTemplateDTO[]);
      setList(data);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); }, []);

  const startCreate = () => {
    const initialDocType = 'blank';
    setEditing({
      key: '',
      name: '',
      docType: initialDocType,
      defaultName: '未命名文档',
      content: getDefaultContentByDocType(initialDocType),
      enabled: true,
    } as Partial<DocTemplateDTO>);
    setPreviousDocType(initialDocType);
    setShowEdit(true);
  };

  const startEdit = (tpl: DocTemplateDTO) => {
    setEditing(tpl);
    setPreviousDocType(tpl.docType || '');
    setShowEdit(true);
  };

  // 处理文档类型变化
  const handleDocTypeChange = (newDocType: string) => {
    if (!editing) return;
    
    // 如果内容为空或者是之前类型的默认内容，则自动填充新类型的默认内容
    const currentContent = editing.content || '';
    const previousDefaultContent = getDefaultContentByDocType(previousDocType);
    const shouldAutoFill = !currentContent || currentContent.trim() === previousDefaultContent.trim();
    
    setEditing({
      ...editing,
      docType: newDocType,
      content: shouldAutoFill ? getDefaultContentByDocType(newDocType) : currentContent,
    });
    setPreviousDocType(newDocType);
  };

  const confirmSave = async () => {
    if (!editing) return;
    const payload: CreateTemplateParams = {
      key: String(editing.key || '').trim(),
      name: String(editing.name || '').trim(),
      docType: String(editing.docType || 'blank'),
      defaultName: String(editing.defaultName || '未命名文档'),
      content: String(editing.content || ''),
      enabled: editing.enabled !== false,
    };
    if (!payload.key || !payload.name) return;
    if ((editing as DocTemplateDTO)._id) {
      await templateAPI.update((editing as DocTemplateDTO)._id, payload);
    } else {
      await templateAPI.create(payload);
    }
    setShowEdit(false);
    setEditing(null);
    setPreviousDocType('');
    load();
  };

  const remove = async (id: string) => {
    if (!confirm('确定删除该模板吗？')) return;
    await templateAPI.delete(id);
    load();
  };

  const rows = useMemo(() => list, [list]);

  return (
    <div className="p-6">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800">模板管理</h2>
        <p className="text-gray-500">新增/编辑/删除模板，并在“新建”菜单中使用</p>
      </div>

      <div className="bg-white rounded-lg shadow p-4 mb-4 flex items-center justify-between">
        <div className="text-sm text-gray-500">
          共 {rows.length} 个模板
        </div>
        <Button variant="primary" onClick={startCreate}>新建模板</Button>
      </div>

      <div className="bg-white rounded-lg shadow overflow-x-auto">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Key</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">名称</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">类型</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">默认名称</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">启用</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase w-48">操作</th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {rows.map(tpl => (
              <tr key={tpl._id}>
                <td className="px-4 py-2 text-sm">{tpl.key}</td>
                <td className="px-4 py-2 text-sm">{tpl.name}</td>
                <td className="px-4 py-2 text-sm">{tpl.docType}</td>
                <td className="px-4 py-2 text-sm">{tpl.defaultName}</td>
                <td className="px-4 py-2 text-sm">{tpl.enabled ? '是' : '否'}</td>
                <td className="px-4 py-2 text-sm">
                  <div className="flex gap-2">
                    <Button size="sm" variant="outline" onClick={() => startEdit(tpl)}>编辑</Button>
                    <Button size="sm" variant="danger" onClick={() => remove(tpl._id)}>删除</Button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <Modal
        isOpen={showEdit}
        onClose={() => { setShowEdit(false); setEditing(null); setPreviousDocType(''); }}
        title={(editing as DocTemplateDTO)?._id ? '编辑模板' : '新建模板'}
        size="lg"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Key</label>
            <Input value={editing?.key || ''} onChange={(e) => setEditing(s => ({ ...(s ?? {}), key: e.target.value } as Partial<DocTemplateDTO>))} />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">名称</label>
              <Input value={editing?.name || ''} onChange={(e) => setEditing(s => ({ ...(s ?? {}), name: e.target.value } as Partial<DocTemplateDTO>))} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">文档类型(docType)</label>
              <select
                className="border rounded px-3 py-2 w-full"
                value={editing?.docType || 'blank'}
                onChange={(e) => handleDocTypeChange(e.target.value)}
              >
                <option value="blank">空白文档</option>
                <option value="sheet">表格文档</option>
                <option value="slide">演示文稿</option>
                <option value="mindmap">思维导图</option>
                <option value="meeting-notes">会议纪要</option>
                <option value="project-plan">项目计划</option>
                <option value="product-detail">商品详情文档</option>
                <option value="campaign-plan">活动策划文档</option>
                <option value="knowledge-base">知识库文档</option>
                <option value="tech-doc">技术文档</option>
                <option value="product-manual">产品说明</option>
              </select>
              <p className="mt-1 text-xs text-gray-500">选择文档类型后，将自动填充对应的默认结构</p>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">默认名称</label>
              <Input value={editing?.defaultName || ''} onChange={(e) => setEditing(s => ({ ...(s ?? {}), defaultName: e.target.value } as Partial<DocTemplateDTO>))} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">启用</label>
              <select
                className="border rounded px-3 py-2 w-full"
                value={editing?.enabled ? '1' : '0'}
                onChange={(e) => setEditing(s => ({ ...(s ?? {}), enabled: e.target.value === '1' } as Partial<DocTemplateDTO>))}
              >
                <option value="1">是</option>
                <option value="0">否</option>
              </select>
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">内容（HTML/Markdown）</label>
            <textarea
              className="w-full h-48 p-3 border rounded"
              value={editing?.content || ''}
              onChange={(e) => setEditing(s => ({ ...(s ?? {}), content: e.target.value } as Partial<DocTemplateDTO>))}
            />
          </div>
          <div className="flex justify-end gap-3">
            <Button variant="outline" onClick={() => { setShowEdit(false); setEditing(null); setPreviousDocType(''); }}>取消</Button>
            <Button variant="primary" onClick={confirmSave}>保存</Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default TemplateManage;


